package com.example.composableexample.uistate.flowstate

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlin.random.Random

data class DiceUiState(
    val firstDieValue: Int? = null,
    val secondDieValue: Int? = null,
    val numberOfERolls: Int = 0
)


class DiceRollViewModel(private val defaultDispatcher: CoroutineDispatcher = Dispatchers.Default) : ViewModel() {
    private val _uiState = MutableStateFlow(DiceUiState())
    val uiState: StateFlow<DiceUiState> = _uiState.asStateFlow()

    fun rollDice() {
        viewModelScope.launch {
            // 执行其他协程操作
            // ......

            // 执行后台线程操作
            withContext(defaultDispatcher) {
                _uiState.update { currentState ->
                    currentState.copy(
                        firstDieValue = Random.nextInt(from = 1, until = 7),
                        secondDieValue = Random.nextInt(from = 1, until = 7),
                        numberOfERolls = currentState.numberOfERolls + 1
                    )
                }
            }
        }
    }
}

data class AddEditTaskUiState(
    val title: String = "",
    val description: String = "",
    val isTaskCompleted: Boolean = false,
    val isLoading : Boolean = false,
    val userMessage: String? = null,
    val isTaskSaved: Boolean = false
)

data class Task(
    val title: String,
    val description: String
)


class AddEditTaskViewModel: ViewModel() {
    private val _uiState = MutableStateFlow(AddEditTaskUiState())
    val uiState: StateFlow<AddEditTaskUiState> = _uiState.asStateFlow()

    private fun createNewTask() {
        viewModelScope.launch {
            val newTask = Task(uiState.value.title, uiState.value.description)
            try {
                // taskRepository.saveTask(newTask)
                _uiState.update {
                    it.copy(
                        isTaskCompleted = true
                    )
                }
            } catch (cancelException: CancellationException) {
                throw cancelException
            } catch (exception: Exception) {
                _uiState.update {
                    it.copy(
                        userMessage = exception.message
                    )
                }
            }
        }
    }
}